package com.cheche.dn.common.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Jsonp 支持
 * Created by cheshun on 15/2/10.
 */
public class JsonpFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		String callback = request.getParameter("callback");
		if (callback == null || callback.equals("")) {
			filterChain.doFilter(request, response);
			return;
		}
		CharResponseWrapper crw = new CharResponseWrapper((HttpServletResponse)response);
		filterChain.doFilter(request, crw);
		String content = crw.getContent();
		content = String.format("%s(%s)", callback, content);
		PrintWriter out = response.getWriter();
		out.write(content);
	}

	@Override
	public void destroy() {}
}
